package br.cs.correspodente.conexao;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import br.cs.correspondente.servicos.ResourceBundleUtil;

public class FactoryConnection {

	private FactoryConnection() {

	}

	private static FactoryConnection fabrica;

	public static FactoryConnection getInstance() {
		if(fabrica==null)
			fabrica=new FactoryConnection();
		return fabrica;
	}

	public Connection criaConexao() throws ClassNotFoundException {
		//protocolo //servidor//banco
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://localhost:3306/correspondente";
		String usuario = ResourceBundleUtil.getPropriedade("USUARIO");
		String senha = ResourceBundleUtil.getPropriedade("SENHA");
		Connection conexao = null;
		try {
			conexao = DriverManager.getConnection(url,usuario,senha);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conexao;
		
//		Class.forName("com.mysql.jdbc.Driver");
//		String url = "jdbc:mysql://localhost:3306/daocesb";
//		String usuario = "root";
//		String senha = "root";
//		Connection conexao = null;
//		try {
//			conexao = DriverManager.getConnection(url,usuario,senha);
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
//		return conexao;
	}
	public EntityManager criaConexaoEntity(){
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPA_UNIT");
		return emf.createEntityManager();
	}
	public void closeConexao(Connection con){
		try {
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public void closeConexao(Connection con, PreparedStatement stm){
		
		try {
			stm.close();
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void closeConexao(Connection con, PreparedStatement stm, ResultSet rs){
		
		try {
			rs.close();
			stm.close();
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}